from pyjenkinsci.artifact import artifact
from pyjenkinsci import constants as pyhudson_constants
from pyjenkinsci.exceptions import ArtifactsMissing, TimeOut, UnknownJob, BadURL
from pyjenkinsci.fingerprint import fingerprint
from pyjenkinsci.jenkinsobject import jenkinsobject
from pyjenkinsci.job import job
from pyjenkinsci.utils.urlopener import mkurlopener
from pyjenkinsci.view import view
import logging
import os
import time
import urlparse


log = logging.getLogger(__name__)

class jenkins( jenkinsobject ):
    """
    Represents a hudson environment.
    """
    def __init__(self, baseurl, proxyhost=None, proxyport=None, proxyuser=None, proxypass=None):
        self.proxyhost = proxyhost
        self.proxyport = proxyport
        self.proxyuser = proxyuser
        self.proxypass = proxypass
        
        jenkinsobject.__init__( self, baseurl )
    
    def getProxyAuth(self):
        return ( self.proxyhost, self.proxyport, self.proxyuser, self.proxypass )
    
    def getOpener( self ):
        return mkurlopener( *self.getProxyAuth() )
    
    def validateFingerprint( self, id ):
        obj_fingerprint = fingerprint( self.baseurl, id, hudson=self )
        obj_fingerprint.validate()
        log.info("Hudson says %s is valid" % id)
        
    def get_artifact_data( self, id ):
        obj_fingerprint = fingerprint( self.baseurl, id )
        obj_fingerprint.validate()
        return obj_fingerprint.getInfo()
    
    def validate_fingerprint_for_build(self, digest, filename, job, build ):#
        obj_fingerprint = fingerprint( self.baseurl, digest, hudson=self )
        return obj_fingerprint.validate_for_build( filename, job, build )
    
    def getHudsonObject(self):
        return self
    
    def getJobs( self ):
        """
        Fetch all the build-names on this Hudson server.
        """
        for info in self._data["jobs"]:
            yield info["name"], job( info["url"], info["name"], hudson=self )
    
    def iteritems(self):
        return self.getJobs()
    
    def iterkeys(self):
        for info in self._data["jobs"]:
            yield info["name"]
            
    def keys(self):
        return [ a for a in self.iterkeys() ]
    
    def __str__(self):
        return "Hudson server at %s" % self.baseurl
    
    def _getViews( self ):
        if not self._data.has_key( "views" ):
            pass
        else:
            for viewdict in self._data["views"]:
                yield viewdict["name"], viewdict["url"]
                
    def getViewDict(self):
        return dict( self._getViews() )
    
    def getViewURL( self, str_view_name ):
        try:
            view_dict = self.getViewDict()
            return view_dict[ str_view_name ]
        except KeyError, ke:
            all_views = ", ".join( view_dict.keys() )
            raise KeyError("View %s is not known - available: %s" % ( str_view_name, all_views ) )
    
    def getView(self, str_view_name ):
        view_url = self.getViewURL( str_view_name )
        view_api_url = self.python_api_url( view_url )
        return view( view_api_url , str_view_name, hudson=self )
    
    def __getitem__( self, buildname ):
        """
        Get a build
        """
        for name, job in self.getJobs():
            if name == buildname:
                return job
        raise UnknownJob(buildname)
     

        
